const { request, uploadFile2, wxLogin } = require('../../utils/request')
const getToken = require('../../aliUtils/token.js').getToken
const SpeechTranscription = require('../../aliUtils/st.js')
const AKID = 'LTAI5tEiVB1fqnVmo2ctMYi2'
const AKKEY = '1USsGGtonGOgPvSNj71kefjTxDT6I7'
const aliSpeechUrl = 'wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1'
const APPKEY = '8w519vsOlGEdq8LH'

// index.ts
const {
  getStatusBarAndMenuButtonInfo,
  formatDate_dot,
  isLogin,
  getAuthSetting,
  openSettingModal,
  splitContentForPage,
  formatSeconds,
  getAudioUrl
} = require('../../utils/util')
// 获取应用实例
const app = getApp<IAppOption>()
let curSeconds = 0
let topTotalSeconds = 60
let timeHander = null as any
let recorderManager = null as any
let _audioContext = null as any

// let recordResTimeHandler = null as any
let isCancelRecord = false as boolean
let requestTimeHandler = null as any
let startRecordTimer = null as any
let touchStartTimer = null as any
let secondGuidePopTouchstartEventTouch = null as any
let st = null as any
let smallerOperTimeHandler = null as any
let hiddenMyAudioTimeHandler = null as any
let showRecordPopTimeHandler = null as any
let recordBannerRectTop = 0
let stResult = ''
let tempStResult = ''
let swiperShowRecordTipTimeHandler = null as any
Page({
  data: {
    navigationBarHeight: '87px',
    videoStatus:'paused',
    firstSwiperCurrentIndex: 0,
    hasShowGuide: true, // 是否展示过操作指引
    // demoRecord:null,
    boardPageVisible: !wx.getStorageSync('hadShowBoardPage') || false,
    bigOperationBtnVisible: true,
    needShowPrivacy: false,
    privacyActionSheetVisible: false,
    noteList: [],
    playingAudioUrl: '', // 正在播放的音频url
    userInfo: null,
    showPrivacy: false,
    loading: true,
    inviteData: {
      status: 1, // 1=未完成 2=已完成
      prompt: '邀请5位好友注册，录音延长至3分钟'
    },
    weComStatus: 3, // 企业微信的绑定状态，1=未关注 2=已关注 3=不展示
    sharePanelVisible: false,
    moreToolsActionList: [
      {
        id: 'delete',
        name: '删除'
      },
      {
        id: 'update',
        name: '修改'
      }
    ],
    moreToolsActionSheetVisible: false, // 更多功能操作面板

    curSelectedRecord: null, // 当前被选中的录音
    selfDialogData: {
      actionType: '',
      title: '提示',
      content: '是否删除该录音？',
      cancelText: '取消',
      confirmText: '确定',
      showCancelBtn: true,
      showConfirm: true,
      confirmColor: '#FF6B6B',
      cancelColor: '#333333',
      visible: false
    },
    childSwiperCurrentIndex: 0,
    invitePopupVisible: false,
    recordProgressVisible: false,
    curTimeStr: formatSeconds(curSeconds),
    limitTimeStr: formatSeconds(topTotalSeconds),
    showPureTime: true,
    submitBtnBgWidth: '0%',
    inRecord: false,
    audioTempPath: '',
    audioServerPath: '',
    cancelRecordBtnRect: null,
    // recordBannerRect: null,
    videoDuration: 23,
    hasRecordAuth: false,
    willCancelRecord: false, // 判断用户是否将要取消录音
    firstGuideVisible: false,
    secondGuideVisible: false,
    recordType: 1, // 1实时录音，2录音文件
    aliToken: null,
    // tempStResult: '',
    // stResult: '',
    
    videoLoaded:false,
    toastVisible:false,
    toastTxt:'录音时间太短了',
    isInviteShare:false,
    curHiddenAudioIndex:null,
    myAudioHiddenTimeNum: 60000,
    isSubmitRecord: false,
    // 当前页面是否录过音
    // 当前是否是春节活动
    isSpringFestival: false,
    swiperShowRecordTip: false,
    // showSwiperContent:true,  // 是否显示swiper内容， 添加这个变量是为了解决删除某个swiper后，swiper不重新渲染的bug
  },

  //options(Object)
  onLoad: function () {
    console.log('index onLoad')
    let boardPageVisible = !wx.getStorageSync('hadShowBoardPage') || false
    this.setData({
      boardPageVisible 
    })
    // 不显示引导页，则显示大按钮
    if(!boardPageVisible){
      // 显示大按钮,5s后变成小按钮
      this.smallerOperationBtn()
    }
    this.getNavigationBarHeight()
    // 获取隐私协议
    this.getPrivacyStatus()
    // 初始化token和初始化语音识别
    this.getAliToken()
    // 初始化录音器
    this.initRecordManager()
    setTimeout(()=>{
      this.resolveLoading()
    },3000)
    
    
  },

  onShow: function () {
    console.log('index onShow')
    this.indexlogin()
    // 获取用户权限
    this.getSettingStatus()
    // 测试
    // this.testRequest()
    
    this.initVar()
    this.initAudioContext()

    // 显示引导页
    // this.showFirstGuidePopup()
  
    
  },
  onUnload: function () {
    console.log('onUnload')
    // this.freezePage()
  },
  onHide: function () {
    console.log('index onHide')
    this.freezePage()
    // 停止子swiper的运行
  },
  initVar(){
    // console.log('recorderManager:',recorderManager)
    // if(recorderManager){
    //   recorderManager.stop()
    // }
    this.setData({
      inRecord:false
    })
  },
  hiddenMyAudio(){
    this.setData({
      curHiddenAudioIndex: this.data.firstSwiperCurrentIndex
    })
    if(hiddenMyAudioTimeHandler){
      clearTimeout(hiddenMyAudioTimeHandler)
    }
    console.log('myAudioHiddenTimeNum:',this.data.myAudioHiddenTimeNum)
    hiddenMyAudioTimeHandler = setTimeout(()=>{
      this.showMyAudio()
    },this.data.myAudioHiddenTimeNum)
  },
  showMyAudio(){
    this.setData({
      curHiddenAudioIndex: null
    })
    
  },
  selfShowToast(txt:string){
    this.setData({
      toastTxt:txt,
      toastVisible:true
    })
    setTimeout(()=>{
      this.selfHideToast()
    },3000)
  },
  selfHideToast(){
    this.setData({
      toastVisible:false
    })
  },
  pageScrollToFirstSwiper(){
    this.setData({
      firstSwiperCurrentIndex:0
    })
  },
  freezePage(){
    console.log('freezePage _audioContext')
    // console.log('freezePage _audioContext.destroy:',_audioContext.destroy)
    try {
      if(_audioContext && _audioContext.destroy){
        _audioContext.destroy()
      }
    } catch (error) {
      
    }
    
    this.stopSwiperAutoPlay()
    this.cancelRecord()
  },
  getNavigationBarHeight(){
    let { statusBarHeight,menuBarHeight} =  getStatusBarAndMenuButtonInfo()
    this.setData({
      navigationBarHeight:(statusBarHeight + menuBarHeight) + 'px'
    })
  },


  videoTimeUpdate(event: any) {
    let currentTime = event.detail.currentTime
    let duration = event.detail.duration
    let videoDuration = Math.ceil(duration - currentTime)
    if(videoDuration <= 0){
      this.hideBoardPage()
    }
    this.setData({
      videoDuration: Math.ceil(duration - currentTime)
    })
  },
  firstSwiperChange(event: any) {
    // console.log('firstSwiperChange')
    let current = event.detail.current
    this.setData({
      firstSwiperCurrentIndex: current,
      curSelectedRecord: this.data.noteList[current]
    })
    this.stopAllAudio()
    // console.log('this.data.noteList[current]:',this.data.noteList[current])
    
  },
  childSwiperChange() {
    console.log('childSwiperChange')
  },

  async getCancelRecordBtnRect() {
    let that = this as any
    return new Promise((resolve) => {
      wx.createSelectorQuery()
        .select('#cancelRecordBtn')
        .boundingClientRect(function (rect) {
          that.setData({
            cancelRecordBtnRect: rect
          })
          resolve(rect)
        })
        .exec()
    })
  },
  async getRecordBannerRect() {
    // let that = this as any
    return new Promise((resolve) => {
      setTimeout(()=>{
        wx.createSelectorQuery()
        .select('#recordBanner')
        .boundingClientRect(function (rect) {
          console.log('getRecordBannerRect rect:',rect)
          // that.setData({
          //   recordBannerRect: rect
          // })
          if(rect){
            recordBannerRectTop = rect.top
            resolve(rect.top)
          }else {
            resolve(null)
          }
        })
        .exec()
      },1000)
      
    })
  },

  async mainTouchEnd(event: any) {
    let that = this as any
    that.showMyAudio()
    clearTimeout(showRecordPopTimeHandler)
    clearTimeout(touchStartTimer)
    // console.log('mainTouchEnd event:',event)
    // console.log('mainTouchEnd inRecord:',this.data.inRecord)
    
    // console.log('mainTouchEnd this.data.inRecord:',this.data.inRecord)
    if (event.target.id === 'authRecordBtn'  && that.data.inRecord) {
      
      
      // console.log('mainTouchEnd:',event)

      // let cancelRecordBtnRect = this.data.cancelRecordBtnRect
      // if(!cancelRecordBtnRect){
      //   cancelRecordBtnRect = await this.getCancelRecordBtnRect()
      // }
      // if(!cancelRecordBtnRect){
      //   this.cancelRecord()
      //   selfShowToast({
      //     title: '录音时间太短',
      //     icon:'none'
      //   })
      //   return
      // }
      // let touch = event.changedTouches[0]
      // let { pageX , pageY } = touch

      // // 在删除按钮上释放，则取消录音，否则则正常提交录音
      // if(pageX > cancelRecordBtnRect.left && pageX < cancelRecordBtnRect.right && pageY > cancelRecordBtnRect.top && pageY < cancelRecordBtnRect.bottom){
      //   this.cancelRecord()
      // }else {
      //   this.recordFinish()
      // }
      
      if (!recordBannerRectTop) {
        await that.getRecordBannerRect()
      }
      console.log('recordBannerRectTop:',recordBannerRectTop)
      if (!recordBannerRectTop) {
        // @ts-ignore
        that.selfShowToast('录音时间太短了')
        this.cancelRecord()
        return
      }
      let touch = event.changedTouches[0]
      let pageY = touch.pageY
      // console.log('pageY:',pageY,',recordBannerRect.top:',recordBannerRect.top)

      if (pageY < recordBannerRectTop) {
        this.cancelRecord()
      } else {
        this.recordFinish()
      }
    }else {
      this.cancelRecord()
    }
  },

  async mainTouchMove(event: any) {
    if(!this.data.recordProgressVisible){
      return 
    }
    // console.log('mainTouchMove:',event)
    let that = this as any
    // console.log('mainTouchMove:',event.target.id,)
    if (event.target.id === 'authRecordBtn' && that.data.inRecord) {
      
      if (!recordBannerRectTop) {
        await that.getRecordBannerRect()
      }
      console.log('mainTouchMove recordBannerRectTop:',recordBannerRectTop)
      if(!recordBannerRectTop){
        return
      }
      let touch = event.touches[0]
      let pageY = touch.pageY
      if (pageY < (recordBannerRectTop - 20)) {
        that.setData({
          willCancelRecord: true
        })
      } else {
        that.setData({
          willCancelRecord: false
        })
      }
    }
  },
  showMoreActionSheet(event: any) {
    // console.log('showMoreActionSheet event:',event)
    let curSelectedRecord = event.currentTarget.dataset.item
    // 1=未完成 2=已完成
    if (curSelectedRecord.status !== 2) {
      wx.showModal({
        title: '提示',
        content: '内容还未生成，请稍后再试',
        showCancel: false
      })
      return
    }

    this.setData({
      moreToolsActionSheetVisible: true,
      curSelectedRecord: curSelectedRecord
    })
    this.stopSwiperAutoPlay()
    // console.log('data:',this.data)
  },
  hideMoreActionSheet() {
    this.setData({
      moreToolsActionSheetVisible: false
    })
    this.reStartSwiperAutoPlay()

    
  },

  hideSelfDialog() {
    let selfDialogData = Object.assign({}, this.data.selfDialogData)
    delete selfDialogData.actionType
    selfDialogData.visible = false
    this.setData({
      selfDialogData: selfDialogData
    })
  },
  videoPlay(){
    console.log('videoPlay')
    this.setData({
      videoStatus:'playing'
    })
    
  },
  videoLoadFn(event:any){
    // console.log('videoLoadFn:',Math.ceil(event.detail.duration))
    if(this.data.boardPageVisible){
      if(this.data.videoStatus ==='paused'){
        let videoContext = wx.createVideoContext('introVideo')
        if(videoContext){
          videoContext.play()
        }
        setTimeout(()=>{
          this.setData({
            videoStatus:'playing',
            videoLoaded: true,
            videoDuration: Math.ceil(event.detail.duration)
          })
        },1000)
        
      }
    }
    
    
  },
  videoEnd() {
    console.log('videoEnd')
    this.hideBoardPage()
  },
  smallerOperationBtn(){
    console.log('smallerOperationBtn')
    smallerOperTimeHandler = setTimeout(()=>{
      this.setData({
        bigOperationBtnVisible: false
      })
      wx.setStorageSync('hadShowBigOperationBtn',true)
    },8000)
    
  },

  dialogConfirmActionTap() {
    let selfDialogData = this.data.selfDialogData
    if (selfDialogData.actionType === 'deleteNote') {
      this.deleteThisRecord()
    }
  },

  setShareItem(event: any) {
    console.log('setShareItem')
    let that = this as any
    
    this.stopSwiperAutoPlay()
    setTimeout(()=>{
      that.reStartSwiperAutoPlay()
    },5000)
    if(this.data.firstGuideVisible){
      this.closeFirstGuidePopup()
    }
    
  },
  guideJumpTemplatePage(event: any) {
    let curSelectedRecord = this.data.noteList[0]
    console.log('curSelectedRecord:',curSelectedRecord)
    if (curSelectedRecord.status !== 2) {
      wx.showModal({
        title: '提示',
        content: '内容还未生成，请稍后再试',
        showCancel: false
      })
      return
    }
    wx.navigateTo({
      url:
        '/pages/singleTemplate/singleTemplate?recordId=' +
        curSelectedRecord.id +
        '&shareChannel=2&templateCode=' +
        curSelectedRecord.templateCode + '&cjFlag=' + curSelectedRecord.cjFlag,
    })
    this.stopSwiperAutoPlay()
    this.closeFirstGuidePopup()
  },
  hideSharePanel() {
    this.setData({
      sharePanelVisible: false
    })
  },
  hideBoardPage() {
    this.setData({
      boardPageVisible: false
    })
    wx.setStorageSync('hadShowBoardPage', true)
    // 如果记录为空，则播放音频
    if (this.data.noteList.length == 0 && !this.data.needShowPrivacy) {
      this.playStartAudio()
    }
    // 如通过有隐私协议，则显示隐私协议
    if(!this.data.needShowPrivacy){
      this.smallerOperationBtn()
    }
    
  },
  async indexlogin() {
    let that = this as any
    if (!isLogin()) {
      await wxLogin()
    }
    // this.getDemoRecord()
    this.initDataWhenLogin()
    // 获取请求参数
    let launchOptions = wx.getEnterOptionsSync()
    // console.log('indexlogin launchOptions:',launchOptions)
    let query = launchOptions.query
    if (query.jtUserId) {
      this.bingJingTanUser(query.jtUserId)
    } else {
      // 查询当前用户的邀请任务
      that.getInviteStatus()
      // 获取企业微信绑定状态
      that.getWeComStatus()
    }

  },

  deleteThisRecord() {
    let that = this as any
    let curSelectedRecord = this.data.curSelectedRecord
    // 如果录音正在播放，则停止播放录音
    // if (this.data.playingAudioUrl === curSelectedRecord.voiceAddress) {
    //   this.stopAllAudio()
    // }
    this.stopAllAudio()
    // this.setData({
    //   showSwiperContent: false,
    //   noteList:[]
    // })
    request({
      url: '/records/' + curSelectedRecord.id,
      method: 'delete',
      success: () => {
        that.selfShowToast('删除成功')
        that.setData({
          isSubmitRecord: true
        },()=>{
          that.getHistoryRecord()
        })
        
      }
    })
  },
  initDataWhenLogin() {
    let that = this as any
    // 获取历史日志数据
    that.getHistoryRecord()
    // 重新查询用户信息
    that.getUserInfo()
  },
  // 绑定鲸探用户
  bingJingTanUser(jtUserId: string) {
    let that = this as any
    request({
      url: '/users/jingtan-bind?jingtanId=' + jtUserId,
      method: 'POST',
      data: {
        jingtanId: jtUserId
      },
      success: function (res: any) {
        console.log('jingtan res:', res)

        setTimeout(() => {
          // 查询当前用户的邀请任务
          that.getInviteStatus()
          // 获取企业微信绑定状态
          that.getWeComStatus()
          that.getUserInfo()
        }, 300)
      },
      fail(err: any) {
        console.log('error:', err)
      }
    })
  },
  getWeComStatus() {
    request({
      url:
        '/users/e-wechat/follow-status?env=' + (app.globalData.isDev ? 2 : 1),
      success: (data: any) => {
        // console.log('getWeComStatus data:',data)
        this.setData({
          weComStatus: data.status
        })
      },
      complete: () => {
        this.resolveLoading()
      }
    })
  },

  getInviteStatus() {
    // 获取当前用户邀请任务
    let that = this as any
    request({
      url: '/ui-task/current',
      success: (data: any) => {
        // console.log('getInviteStatus data:',data)
        let isSpringFestival = new Date() < new Date(data.cjEndTime)
        that.setData({
          inviteData: data,
          myAudioHiddenTimeNum:data.hideButtonTime * 1000 || 60000,
          isSpringFestival
        })
        wx.setStorageSync('isSpringFestival', isSpringFestival)
      }
    })
  },

  jumpTemplatePage(eventOrItem: any) {
    let curSelectedRecord = eventOrItem.currentTarget.dataset.item
    if (curSelectedRecord.status !== 2) {
      wx.showModal({
        title: '提示',
        content: '内容还未生成，请稍后再试',
        showCancel: false
      })
      return
    }
    wx.navigateTo({
      url:
        '/pages/singleTemplate/singleTemplate?recordId=' +
        curSelectedRecord.id +
        '&shareChannel=2&templateCode=' +
        curSelectedRecord.templateCode + '&cjFlag=' + curSelectedRecord.cjFlag,
    })

    // wx.setStorageSync('/index/templateData',{
    //   title:recordData.title,
    //   content:recordData.content
    // })
    this.stopSwiperAutoPlay()
  },

  showInviteBanner() {
    this.setData({
      invitePopupVisible: true,
      isInviteShare:true
    })
  },
  hideInviteBanner() {
    console.log('hideInviteBanner')

    this.setData({
      invitePopupVisible: false
    })
    setTimeout(()=>{
      this.setData({
        isInviteShare:false
      })
    },5000)
  },
  editNote() {
    this.hideMoreActionSheet()
    let item = this.data.curSelectedRecord
    wx.navigateTo({
      url: '/pages/changeContent/changeContent?id=' + item.id
    })
  },
  deleteRecord(event: any) {
    let curSelectedRecord = event.currentTarget.dataset.item
    this.setData({
      curSelectedRecord: curSelectedRecord
    })
    this.deleteNote()
  },
  deleteNote() {
    
    this.hideMoreActionSheet()
    setTimeout(()=>{
      let selfDialogData = this.data.selfDialogData
      selfDialogData.visible = true
      selfDialogData.actionType = 'deleteNote'
      selfDialogData.title = '提示'
      selfDialogData.content = `确定要删除这条记录吗？`
      this.setData({
        selfDialogData: selfDialogData
      })
    },100)
    
  },
  getPrivacyStatus() {
    // 检查用户是否同意了隐私协议
    wx.getPrivacySetting({
      success: (res) => {
        // console.log('getPrivacySetting res:',res)
        // alert('getPrivacySetting res:' + JSON.stringify(res))
        if (res.needAuthorization) {
          // 需要弹出隐私协议
          this.setData({
            needShowPrivacy: true,
          })
          clearTimeout(smallerOperTimeHandler)
        } else {
          this.setData({
            needShowPrivacy: false,
          })
        }
      },
      fail: (error) => {
        // alert('getPrivacySetting error:' + JSON.stringify(error))
      },
      complete: () => {}
    })
  },
  stopAllAudio() {
    this.setData({
      playingAudioUrl: String(new Date().getTime())
    })
    if(_audioContext && !_audioContext.paused){
      _audioContext.stop()
    }
  },
  resolveLoading(callback: any) {
    setTimeout(() => {
      this.setData(
        {
          loading: false
        },
        () => {
          callback && callback()
        }
      )
    }, 100)
  },
  getUserInfo() {
    request({
      url: '/users/current-user',
      method: 'GET',
      success: (data: any) => {
        topTotalSeconds = data.recordingDuration
        this.setData({
          userInfo: data,
          limitTimeStr: formatSeconds(data.recordingDuration)
        })
        // console.log('getUserInfo:',data)
        wx.setStorageSync('userInfo', data)
      },
      complete: () => {
        this.resolveLoading()
      }
    })
  },
  postShareData() {
    let curSelectedRecord = this.data.noteList[this.data.firstSwiperCurrentIndex]
    console.log('curSelectedRecord:', curSelectedRecord)
    
    if (curSelectedRecord) {
      let title = ''
      let currentTemplateCode = curSelectedRecord.templateCode
      if (currentTemplateCode === 'riji') {
        title = '我记了一篇日记，快来看看吧'
      } else if (currentTemplateCode === 'shige') {
        title = '我作了一首诗，快来看看吧'
      } else if (currentTemplateCode === 'shuxin') {
        title = '我写了一封信，快来看看吧'
      }
      if(curSelectedRecord.cjFlag){
        title = '我写给你的新年贺词，喜欢吗？'
      }
      return new Promise((resolve) => {
        request({
          url: '/record-share',
          method: 'POST',
          data: {
            recordId: curSelectedRecord.id,
            templateCode: curSelectedRecord.templateCode,
          },
          success(rData: any) {
            console.log('postShareData')
            let userInfo = wx.getStorageSync('userInfo')
            let userId = (userInfo && userInfo.id) || ''

            resolve({
              title,
              path:
                '/pages/share/share?inviteUserId=' +
                userId +
                '&shareChannel=2&id=' +
                rData.id
            })
          }
        })
      })
    }
  },
  getDefaultShareData() {
    let curSelectedRecord = this.data.curSelectedRecord
    let title = ''
    if(curSelectedRecord){
      let currentTemplateCode = curSelectedRecord.templateCode
      if (currentTemplateCode === 'riji') {
        title = '我记了一篇日记，快来看看吧'
      } else if (currentTemplateCode === 'shige') {
        title = '我作了一首诗，快来看看吧'
      } else if (currentTemplateCode === 'shuxin') {
        title = '我写了一封信，快来看看吧'
      }
      return {
        title: title,
        imageUrl:null,
        path: '/pages/index/index'
      }
    }
    let appDefaultShareData = app.getDefaultShareData()
    if(title){
      appDefaultShareData.title = title
    }
    return appDefaultShareData
    
  },
  onShareAppMessage() {
    console.log('onShareAppMessage ')
    
    if(this.data.swiperShowRecordTip){
      clearTimeout(swiperShowRecordTipTimeHandler)
      swiperShowRecordTipTimeHandler = setTimeout(() => {
        this.setData({
          swiperShowRecordTip: true
        })
      },5000)
      this.setData({
        swiperShowRecordTip: false
      })
    }
    
    this.hiddenMyAudio()
    if(this.data.isInviteShare){
      let defaultShareData = app.getDefaultShareData()
      console.log('defaultShareData:',defaultShareData)
      return defaultShareData
    }else {
      let defaultShareData = this.getDefaultShareData()
    console.log('defaultShareData2:',defaultShareData)
      return {
        ...defaultShareData,
        promise: this.postShareData()
      }
    }
    
  },


  playThisAudio(event: any) {
    // console.log('playThisAudio:',event.detail.audioUrl)
    
    this.setData({
      playingAudioUrl: event.detail.audioUrl || ''
    })
  },
  parentPlayThisAudio(event:any){
    if(!_audioContext.paused){
      _audioContext.stop()
    }
  },
  jumpSettingPage() {
    wx.navigateTo({
      url: '/pages/setting/setting'
    })
  },


  // // 获取示范记录
  // getDemoRecord(){
  //   let that = this
  //   request({
  //     url:'/sys/demo-record',
  //     method:'GET',
  //     success:(data:any)=>{
  //       that.setData({
  //         demoRecord:data
  //       })
  //     }
  //   })
  // },
  stopSwiperAutoPlay() {
    let childCom = this.selectComponent("#swiperContent"+this.data.firstSwiperCurrentIndex);
    if(childCom){
      childCom.stopAutoplay()
      childCom.resetSwiperCurrentIndex()
    }
  },
  reStartSwiperAutoPlay() {
    let childCom = this.selectComponent("#swiperContent"+this.data.firstSwiperCurrentIndex);
    // console.log('childCom:',childCom)
    if(childCom){
      childCom.playChildSwiper()
    }
  },
 
  initAudioContext(){
    _audioContext = wx.createInnerAudioContext({
      useWebAudioImplement: true 
    }) as any
    _audioContext.onPlay(()=>{
      console.log('playing')
    })
  },
  async playStartAudio(){
    console.log('playStartAudio _audioContext')
    
    

    if(_audioContext){
      if(_audioContext.paused){
        this.stopAllAudio()
        let tempAudioSrc = 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/note-miniProgram/sy-voice1_1.mp3?v=4'
        if(this.data.isSpringFestival){
          tempAudioSrc = 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/note-miniProgram/sy-voice1_1_cj.mp3'
        }
        let audioSrc = await getAudioUrl(tempAudioSrc)
        _audioContext.src = audioSrc
        _audioContext.play()
      }else {
        _audioContext.stop()
        _audioContext.src = ''
      }
    }
  },
  async playGuide1Audio(){
    
    this.stopAllAudio()

    let audioSrc = await getAudioUrl('https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/note-miniProgram/guide/guide-audio1.mp3')

    if(_audioContext){
      if(_audioContext.paused || _audioContext.src != audioSrc){
        _audioContext.src = audioSrc
        _audioContext.play()
        console.log('playGuide1Audio')
      }else {
        _audioContext.stop()
        _audioContext.src = ''
        console.log('stopGuide1Audio')
      }
    }
  },
  async playGuide2Audio(){
    console.log('playGuide2Audio')
    this.stopAllAudio()

    let audioSrc = await getAudioUrl('https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/note-miniProgram/guide/guide-audio2.mp3')

    if(_audioContext){
      if(_audioContext.paused ||  _audioContext.src != audioSrc){
        _audioContext.src = audioSrc
        _audioContext.play()
        console.log('playGuide2Audio')
      }else {
        _audioContext.stop()
        _audioContext.src = ''
        console.log('stopGuide2Audio')
      }
    }
  },
  getHistoryRecord() {
    console.log('getHistoryRecord')
    let that = this
    // 获取历史日志数据
    
    request({
      url: '/user-records',
      method: 'GET',
      success: (data: any) => {
        this.resolveLoading()
        console.log('records:',data)
        if (data.length === 0) {
          // 记录为空，则显示引导语音,且播放音频
          if(!this.data.boardPageVisible && !this.data.needShowPrivacy){
            this.playStartAudio()
          }
          this.setData({
            firstSwiperCurrentIndex:0,
            firstSwiperPindex:0,
            noteList:[],
            showSwiperContent:  true
          })
        } else {
          let noteList = [] as any
          data.forEach((item: any) => {
            noteList = noteList.concat(item.records)
          })
          // 对数据进行过滤，减少内存
          // noteList.forEach((item:any)=>{
          //   item.templateCode= item.cjFlag===1 ? 'spring' : item.templateCode
          // })

          // 对日期和内容进行格式化
          let swiperShowRecordTip = noteList.length >= 1 && noteList.length <= 2
          console.log('swiperShowRecordTip:',swiperShowRecordTip)
          noteList.forEach((item: any) => {
            if(item.status===1){
              item.title="请稍等",
              item.content="「魔豆」正在处理您说的话"
            }
            item.createTimeStr = formatDate_dot(item.createTime)
            
            
            item.pageList = splitContentForPage(item,{
              riji_firstPageRowNum: swiperShowRecordTip ? 8 : 10,
              riji_otherPageRowNum: swiperShowRecordTip ? 10 : 12,
              shuxin_firstPageRowNum: swiperShowRecordTip ? 6 : 8,
              shuxin_otherPageRowNum: swiperShowRecordTip ? 8 : 8,
              shige_firstPageRowNum: swiperShowRecordTip ? 6 : 8,
              shige_otherPageRowNum: swiperShowRecordTip ? 6 : 8,
              firstPageRowNum: swiperShowRecordTip ? 10 : 12,
              otherPageRowNum: swiperShowRecordTip ? 10 : 12,
              
            })
            // 如果设计诗歌，则添加contlins
            if(item.templateCode === 'shige'){
              item.contlines = item.content.split('\n').length
            }
           
          })
          // 只有增删的时候，才会刷新页面，改写的时候不刷新
          if(this.data.isSubmitRecord){
            that.setData({
              firstSwiperCurrentIndex:0,
              firstSwiperPindex:0,
              isSubmitRecord:false
            })
          }
          
          let hadShowFirstGuidePopup = wx.getStorageSync(
            'hadShowFirstGuidePopup'
          )
          
          // 比如是录音过，才能显示引导页，避免一进来就显示引导页
          if (noteList.length === 1 && !hadShowFirstGuidePopup && app.globalData.hasRecorded) {
            wx.setStorageSync('hadShowFirstGuidePopup', true)
            this.showFirstGuidePopup()
          }
          let hadShowSecondGuidePopup = wx.getStorageSync(
            'hadShowSecondGuidePopup'
          )
          // console.log('noteList.length:',noteList.length)
          // console.log('hadShowSecondGuidePopup:',hadShowSecondGuidePopup)
          // console.log('hasRecorded:',app.globalData.hasRecorded)
          if (noteList.length === 2 && !hadShowSecondGuidePopup && app.globalData.hasRecorded) {
            wx.setStorageSync('hadShowSecondGuidePopup', true)
            this.showSecondGuidePopup()
          }
          console.log('noteList.length:',noteList.length)

          // 插入广告图，如果notelist等于2 ，则只在末尾查一张图，如果大于2，则每3张插入一张，最多插入3张图
          if(noteList.length <= 3){
            noteList.push({
              contentType:'ad',
              adSrc:'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/note-miniProgram/modou_qr.png'
            })
          }else {
            let tempNoteList = [] as any
            let adNums = 0
            for(let i = 0; i < noteList.length; i++){
              if(i !==0 && i % 3 === 0 && adNums < 3){
                tempNoteList.push({
                  contentType:'ad',
                  adSrc:'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/note-miniProgram/modou_qr.png'
                  
                })
                adNums++
              }
              tempNoteList.push(noteList[i])
            }
            noteList = tempNoteList
          }
          console.log('noteList:',noteList)
          // console.log('noteList[0]:',noteList[0])
          that.setData({
            noteList,
            swiperShowRecordTip: swiperShowRecordTip,
          })
        }
      }
    })
  },

  stopTouchmove(event: any) {
    return false
  },

  testUpload() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res: any) => {
        console.log('tempFiles:', res.tempFiles)
        let tempFile = res.tempFiles[0]

        uploadFile2(tempFile.tempFilePath)
      }
    })
  },

  hidePrivacyActionSheet() {
    this.setData({
      privacyActionSheetVisible: false,
    })

  },

  agreePrivacyActionSheet() {
    let that = this as any
    this.hidePrivacyActionSheet()
    this.setData({
      needShowPrivacy: false
    })
    this.smallerOperationBtn()
    if (this.data.noteList.length == 0) {
      this.playStartAudio()
    }
  },
  getSettingStatus(){
    let that = this as any
    wx.getSetting({
      success: (res) => {
        // console.log('getSetting res:', res)
        if (res.authSetting['scope.record']) {
          that.setData({
            hasRecordAuth: true
          })
        } else {
          that.setData({
            hasRecordAuth: false
          })
        }
      }
    })
  },
  // 获取麦克风权限
  getRecordAuth() {
    console.log('getRecordAuth')
    let that  = this as any
  // 获取麦克风权限
      getAuthSetting(
        'scope.record',
        () => {
          console.log('getRecordAuth hasRecordAuth')
          that.setData({
            hasRecordAuth: true
          })
        },
        () => {
          openSettingModal('提示', '请先开启麦克风权限', '去开通')
        }
      )
  },
  rejectPrivacy() {
    this.hidePrivacyActionSheet()
    if(wx.exitMiniProgram){
      wx.exitMiniProgram()
    }else {
      wx.showModal({
        title: '提示',
        content: '用户需同意隐私协议才能使用本小程序',
        showCancel: false,
      })
    }
    
  },
  showPrivacyActionSheet() {
    // 显示用户隐私协议
    this.setData({
      privacyActionSheetVisible: true
    })
  },

  jumpToRecordPage() {
    console.log('jumpToRecordPage')
    wx.navigateTo({
      url: '/pages/record/record'
    })
  },


 
  beforeRecord() {
    console.log('beforeRecord')
    this.stopAllAudio()
  },
  // authRecord:throttle(async function (){
  //   // 未开始录音，则开始录音
  //   if(this.data.inRecord === false){
  //     this.setData({
  //       inRecord:true
  //     })
  //     getAuthSetting('scope.record', this.startRecordFile.bind(this), () => {
  //       openSettingModal('提示', '请先开启麦克风权限', '去开通')
  //     })
  //   }

  // },2000),
  // 处理录音并发,返回true，表示可以实时录音，false就是只能录音
  addRecordConCurrent() {
    // 添加录音并发 1=正常 2=已达上限
    return new Promise((resolve) => {
      request({
        url: '/records/add-real-time?key=' + wx.getStorageSync('openid'),
        method: 'post',
        success(data: any) {
          // 1=正常 2=已达上限
          if (data.status === 1) {
            // 可以实时录音
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail() {
          resolve(false)
        }
      })
    })
  },
  async getAliToken() {
    let token = await getToken(AKID, AKKEY)
    // console.log('getAliToken:',token)
    this.setData(
      {
        aliToken: token
      },
      () => {
        this.initSpeechTranscription()
      }
    )
  },
  async initSpeechTranscription() {
    let that = this
    // console.log('initSpeechTranscription st:',st)
    if (st) {
      return
    }

    st = new SpeechTranscription({
      url: aliSpeechUrl,
      appkey: APPKEY,
      token: this.data.aliToken
    })

    st.on('started', (msg: string) => {
      // console.log('Client recv started',msg)
      // this.setData({
      //   stResult: msg
      // })
    })

    st.on('changed', (res: any) => {
      // console.log('Client recv changed:', res)
      if (res) {
        try {
          let resObj = JSON.parse(res)
          // console.log('changed resObj:',resObj)
          if (resObj.payload) {
            // that.setData({
            //   tempStResult: resObj.payload.result
            // })
            tempStResult = resObj.payload.result
          }
        } catch (error) {
          console.error(error)
        }
      }
    })

    st.on('completed', (msg: string) => {
      // console.log('Client recv completed:', msg)
      // this.setData({
      //   stResult: msg
      // })
    })

    st.on('begin', (res: string) => {
      // 句子开始
      // console.log('Client recv sentenceBegin:', res)
    })

    st.on('end', (res: string) => {
      // console.log('Client recv sentenceEnd:', res)
      // 一句话结束
      // this.setData({
      //   stResult: msg
      // })
      if (res) {
        try {
          let resObj = JSON.parse(res)
          console.log('end Obj:',resObj)
          if (resObj.payload) {
            // that.setData({
            //   stResult: that.data.stResult + resObj.payload.result
            // })
            console.log('end stResult:',stResult)
            console.log('resObj.payload.result:',resObj.payload.result)
            let newResult = stResult + resObj.payload.result
            console.log('newResult:',newResult)
            stResult = newResult
            // that.setData({
            //     stResult: newResult
            //   },()=>{
            //     console.log('end stResult2:',that.data.stResult)
            //   })
          }
        } catch (error) {
          console.error(error)
        }
      }
    })

    st.on('closed', () => {
      console.log('Client recv closed')
    })

    st.on('failed', (msg: string) => {
      // console.log('Client recv failed:', msg)
      // this.setData({
      //   stResult: msg
      // })
    })
  },
  async startRealTimeRecord() {
    // 开始录音

    if (!this.data.aliToken) {
      await this.getAliToken()
    }
    // 开始录音
    if (!st) {
      this.initSpeechTranscription()
    }
    // console.log('startRealTimeRecord recorderManager:',recorderManager)
    if (!recorderManager) {
      this.initRecordManager()
    }

    //
    // console.log('inRecord:',this.data.inRecord)
    if (!this.data.inRecord) {
      console.log('startRealTimeRecord inRecord 点击太快')
      // 正在记录，避免重复打开多次
      return
    }
    console.log('开始实时录音')
    this.showRecordPop()

    this.initRecordState()
    this.startCountTime()
    try {
      await st.start(st.defaultStartParams())  
    } catch (error) {
      console.error('st.start error:',error)
    }

    
    console.log('topTotalSeconds:',topTotalSeconds)
    recorderManager.start({
      duration: topTotalSeconds * 1000,
      sampleRate: 16000,
      format: 'mp3',
      frameSize: 4,
      encodeBitRate: 96000,
      numberOfChannels: 1
    })
  },
  async authRecord() {
    console.log('authRecord inRecord:',this.data.inRecord)
    let that = this as any
    that.stopAllAudio()
    if (!that.data.inRecord) {
      // console.log('authRecord')
      clearTimeout(touchStartTimer)
      touchStartTimer = setTimeout(async () => {
        console.log('timeout in authRecord')
        that.stopSwiperAutoPlay()
        let canRealTimeRecord = await that.addRecordConCurrent()
        // canRealTimeRecord = false
        if (canRealTimeRecord) {
          
          that.setData({
            recordType: 1,
            inRecord: true,
          },()=>{
            that.startRealTimeRecord()
          })
          
        } else {
          
          that.setData({
            recordType: 2,
            inRecord: true,
          },()=>{
            that.startRecordFile()
          })
        }
        // 设置overflow 禁止页面滚动
        try {
          // @ts-ignore
          wx.setPageStyle({
            style: {
              overflow: 'hidden' // ‘auto’
            }
         })
        } catch (error) {
          
        }
        

      }, 600)
    }
  },
  cancelAuthRecord() {
    console.log('cancelAuthRecord')
    clearTimeout(touchStartTimer)
    clearTimeout(showRecordPopTimeHandler)
    setTimeout(()=>{
      this.hideRecordPop()
      if(recorderManager){
        recorderManager.stop()
      }
      if(st){
        st.close()
      }
    },300)
  },


  agreePrivacyAuthorization() {
    // 用户同意隐私协议
    console.log('用户同意隐私协议')
    this.stopAllAudio()

    // 弹出隐私协议弹窗
    this.showPrivacyActionSheet()

    // this.authRecord()
  },
  jumpArticle(event: any) {
    const id = event.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/article/article?id=' + id
    })
  },
  testRequest() {
    wx.request({
      url: 'https://d-record-api.wanhuhealth.com/wechatapp/unionid',
      method: 'POST',
      success(res) {
        console.log('testRequest res:', res)
      },
      fail(err) {
        console.log('testRequest err:', err)
      }
    })
  },
  cancelRecord() {
    console.log('cancelRecord')
    this.hideRecordPop()
    isCancelRecord = true
    this.recordFinish()
  },
  startCountTime() {
    let that = this
    if (timeHander) {
      clearInterval(timeHander)
    }
    curSeconds = 0
    timeHander = setInterval(() => {
      curSeconds++
      // console.log('curSeconds:',curSeconds)
      if (curSeconds >= topTotalSeconds) {
        clearInterval(timeHander)
        that.recordFinish()
        that.setData({
          submitBtnBgWidth: '100%',
          curTimeStr: formatSeconds(topTotalSeconds)
        })
      } else {
        if (topTotalSeconds - curSeconds <= 10) {
          let countTimeNum = this.data.countTimeNum - 1
          this.setData({
            showPureTime: false,
            countTimeNum
          })
        }
        that.setData({
          submitBtnBgWidth:
            Math.floor((curSeconds / topTotalSeconds) * 100) + '%',
          curTimeStr: formatSeconds(curSeconds)
        })
      }
    }, 1000)
  },
  stopCountTime() {
    if (timeHander) {
      clearInterval(timeHander)
    }
  },

  async recordFinish() {
    if (startRecordTimer) {
      clearTimeout(startRecordTimer)
    }
    if (!this.data.inRecord) {
      return
    }

    // 停止计时
    this.stopCountTime()
    // 录音结束

    this.setData({
      voiceAnimate: false,
      countTimeNum: 11,
      showPureTime: true,
      inRecord: false
    })
    // 只有实时录音才调用stop
    if (recorderManager) {
      recorderManager.stop()
    }
    if (st && st._client) {
      // console.log('recordFinish st close：',st)
      // 延时关闭，避免数据还在传输中就被突然关闭
      try {
        setTimeout(() => {
          st.close()
        }, 3000)
      } catch (error) {
        console.log('st close error:', error)
      }
      
    }
    // 删除录音并发
    this.removeRecordConCurrent()
    this.reStartSwiperAutoPlay()
    // 录音文件直接关闭弹层
    // console.log('recordFinish 类型和时间:',this.data.recordType,curSeconds)
    if(this.data.recordType ===2){
      this.hideRecordPop()
    }else {
      if(curSeconds < 2){
        this.hideRecordPop()
      }
    }
    try {
      // @ts-ignore
      wx.setPageStyle({
        style: {
          overflow: 'auto' // ‘auto’
        }
     })
    } catch (error) {
      
    }
  },
  removeRecordConCurrent() {
    let openid = wx.getStorageSync('openid')
    if (openid) {
      // 获取录音并发
      request({
        url: '/records/remove-real-time?key=' + openid,
        method: 'post',
        success(data: any) {
          console.log('删除录音并发')
        },
        fail(error: any) {
          console.log('删除录音并发失败：', error)
        }
      })
    }
  },

  showRecordPop() {
    let that = this as any
    clearTimeout(showRecordPopTimeHandler)
    showRecordPopTimeHandler = setTimeout(() => {
      that.setData({
        recordProgressVisible: true
      })
      that.getRecordBannerRect()
    },500)
  },
  hideRecordPop() {
    clearTimeout(showRecordPopTimeHandler)
    this.setData({
      recordProgressVisible: false
    })
  },

  initRecordState() {
    // 把录音相关状态初始化
    curSeconds = 0
    stResult = ''
    tempStResult = ''
    this.setData({
      audioTempPath: '',
      curTimeStr: formatSeconds(curSeconds),
      submitBtnBgWidth: '0%',
      showPureTime: true,
      countTimeNum: 11, // 倒计时提示显示的时间
      willCancelRecord: false
    })
    isCancelRecord = false
  },
  initRecordManager() {
    let that = this as any
    if (!recorderManager) {
      recorderManager = wx.getRecorderManager()
    }

    recorderManager.onFrameRecorded(async (res: any) => {
      // console.log('onFrameRecorded:')
      if (res.isLastFrame) {
        console.log('recorderManager isLastFrame')
        // 录音超时
        // this.completeRecord()
      }

      if (st && this.data.inRecord) {
        // console.log('send ' + res.frameBuffer)
        st.sendAudio(res.frameBuffer)
      }
    })
    // 录音结束
    recorderManager.onStop(async (res: any) => {
      console.log('onStop')
      this.setData({
        inRecord: false
      })
      
      // 如果是取消的，直接返回，不做任何操作
      if (isCancelRecord) {
        that.hideRecordPop()
        return
      }
      console.log('curSeconds:',curSeconds)
      // 录音时间太短
      if (curSeconds < 2) {
        that.selfShowToast('录音时间太短了')
        that.hideRecordPop()
        return
      }
      console.log('录音结束 res:', res)
      // 正常提交
      if (res.tempFilePath) {
        let uploadResUrl = await uploadFile2(res.tempFilePath)
        console.log('uploadResUrl :', uploadResUrl)
        that.setData({
          audioTempPath: res.tempFilePath,
          audioServerPath: uploadResUrl
        })
        // 如果是录音文件则直接提交，如果是实时录音，还要获取录音结果再提交
        if (this.data.recordType === 2) {
          that.submitRecordResult()
        } else {
          // that.startAiOptimize()
          // 等当前任务结束之后再操作
          wx.showLoading({
            title: '奋笔疾书中...',
            mask: true
          })
          setTimeout(() => {
            that.startAiOptimize()
          }, 1000)
        }
        app.globalData.hasRecorded = true
      }
    })
  },

  startRecordFile() {
    console.log('startRecordFile')
    if(!this.data.inRecord){
      console.log('点击太快')
      return 
    }
    // 初始化录音状态
    this.initRecordState()
    // 显示录音页面
    this.showRecordPop()
    // 开始录音文件
    clearTimeout(startRecordTimer)
    startRecordTimer = setTimeout(() => {
      this.startCountTime()
      console.log('topTotalSeconds:',topTotalSeconds)
      recorderManager.start({
        duration: topTotalSeconds * 1000,
        sampleRate: 16000,
        format: 'mp3',
        frameSize: 4,
        encodeBitRate: 96000,
        numberOfChannels: 1
      })
    }, 0)
  },
 

  startAiOptimize() {
    let that = this
    if (isCancelRecord) {
      wx.hideLoading()
      that.hideRecordPop()
      return
    }
    console.log('that.data:', that.data)
    console.log('startAiOptimize stResult: ',stResult)
    console.log('startAiOptimize tempStResult: ',tempStResult)
    if (stResult === '') {
      if (tempStResult.trim() === '') {
        wx.hideLoading()
        that.selfShowToast('录音内容为空')
        that.hideRecordPop()
        return
      } else {
        // that.setData({
        //   stResult: that.data.tempStResult
        // })
        stResult = tempStResult
      }
    }
    that.submitRecordResultRealTime()

  },
  submitRecordResult() {
    let that = this as any
    if (!requestTimeHandler) {
      requestTimeHandler = setTimeout(() => {
        requestTimeHandler = null
      }, 1000)
      // this.stopAllAudio()
      // 保存ai生成的结果
      // console.log('this.data:',this.data)
      let reqData = {
        type: this.data.recordType,
        title: '记录生成中',
        content: '非常抱歉，访问人数太多，我们会尽快为您生成结果',
        voiceAddress: this.data.audioServerPath,
        voiceDuration: curSeconds
      }
      console.log('reqData:', reqData)
      request({
        url: '/records',
        method: 'POST',
        data: reqData,
        success: (recordData: any) => {
          console.log('recordData:', recordData)
          this.setData({
            currentRecord: recordData,
            isSubmitRecord:true
          })
          // if(typeof callback === 'function'){
          //   callback(recordData)
          // }else {
          //   this.jumpBackPage(recordData)
          // }

          wx.navigateTo({
            url: '/pages/recordWaiting/recordWaiting?id=' + recordData.id
          })
        },
        complete() {
          requestTimeHandler = null
          that.hideRecordPop()
        }
      })
    }
  },
  submitRecordResultRealTime() {
    // console.log('requestTimeHandler:',requestTimeHandler)
    console.log('submitRecordResultRealTime')
    let that = this as any
    if (!requestTimeHandler) {
      requestTimeHandler = setTimeout(() => {
        requestTimeHandler = null
      }, 100)
      // this.stopAllAudio()
      // 保存ai生成的结果
      // console.log('this.data:',this.data)
      let reqData = {
        type: this.data.recordType,
        title: '记录生成中',
        content: '非常抱歉，访问人数太多，我们会尽快为您生成结果',
        originalContent: stResult,
        voiceAddress: this.data.audioServerPath,
        voiceDuration: curSeconds
      }
      console.log('reqData:', reqData)
      request({
        url: '/records',
        method: 'POST',
        data: reqData,
        success: (recordData: any) => {
          console.log('recordData:', recordData)
          this.setData({
            currentRecord: recordData,
            isSubmitRecord:true
          })
          // if(typeof callback === 'function'){
          //   callback(recordData)
          // }else {
          //   this.jumpBackPage(recordData)
          // }
          // wx.navigateTo({
          //   url: '/pages/recordWaiting/recordWaiting?id=' + recordData.id
          // })
          that.getHistoryRecord()
        },
        complete() {
          requestTimeHandler = null
          that.hideRecordPop()
          wx.hideLoading()
        }
      })
    }
  },
  showFirstGuidePopup() {
    this.setData({
      firstGuideVisible: true
    })
    setTimeout(() => {
      this.closeFirstGuidePopup()
    }, 5000)
    // 播放语音
    this.playGuide1Audio()
  },
  closeFirstGuidePopup() {
    console.log('closeFirstGuidePopup')
    // 只有1个note时，才显示第一个引导页
    this.setData({
      firstGuideVisible: false,
      curSelectedRecord: this.data.noteList[0]
    })
  },
  showSecondGuidePopup() {
    this.setData({
      secondGuideVisible: true
    })
    setTimeout(() => {
      this.closeSecondGuidePopup()
    }, 5000)
    this.playGuide2Audio()
  },
  closeSecondGuidePopup() {
    this.setData({
      secondGuideVisible: false,
      curSelectedRecord: this.data.noteList[1]
    })
  },
  secondGuidePopTouchstart(event: any) {
    // console.log('secondGuidePopTouchstart event:',event)
    secondGuidePopTouchstartEventTouch = event.touches[0]
  },
  secondGuidePopTouchend(event: any) {
    let touch = event.changedTouches[0]
    // console.log('secondGuidePopTouchend event:',event)
    // 判断用户向下滑动
    if (secondGuidePopTouchstartEventTouch.clientY - touch.clientY > 50) {
      console.log('向下滑动')
      this.setData({
        firstSwiperCurrentIndex: this.data.firstSwiperCurrentIndex + 1
      })
      this.closeSecondGuidePopup()
    }
  }
})
export {}
